home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
NetNews Offline 2
/
NetNews Offline Volume 2.iso
/
news
/
comp
/
std
/
c
/
107
< prev
next >
Wrap
Internet Message Format
|
1996-08-06
|
2KB
Path: stingray.mcnc.org!coats
From: coats@mcnc.org (Carlie Coats)
Newsgroups: comp.std.c
Subject: Re: Help, best way to compare doubles
Date: 15 Jan 1996 11:48:52 GMT
Organization: MCNC, RTP, NC
Message-ID: <4ddev4$1vg@stingray.mcnc.org>
References: <4d1k09$aqq@mercury.IntNet.net> <4dbos6$o7q@umbc9.umbc.edu>
NNTP-Posting-Host: robin.mcnc.org
In article <4dbos6$o7q@umbc9.umbc.edu>,
Jonas J. Schlein <schlein@umbc.edu> wrote:
>Jeff Tomich <jtomich@IntNet.net> wrote:
>|> Having a hard time to figure out a function on how to compare doubles.
>|> Any ideas?
>
>I'd go along with what the c.l.c. FAQ has to say about this one:
>
>14.5: What's a good way to check for "close enough" floating-point
> equality?
>
>A: Since the absolute accuracy of floating point values varies, by
> definition, with their magnitude, the best way of comparing two
> floating point values is to use an accuracy threshold which is
> relative to the magnitude of the numbers being compared. Rather
> than
>
> double a, b;
> ...
> if(a == b) /* WRONG */
>
> use something like
>
> #include <math.h>
>
> if(fabs(a - b) <= epsilon * a)
>
> for some suitably-chosen epsilon.
>
> References: Knuth Sec. 4.2.2 pp. 217-8.
As stated, this is dangerous. Perhaps the FAQ needs revision.
Knuth is careful to put absolute value signs on both sides.
For once, he is not careful to consider the case that a is
zero. A safer test is of the form
| a - b | / sqrt( a^2 + b^2 + delta ) < epsilon
or (equvalently, but in decently-efficient C):
( t = a - b )*t < esquared * ( a*a + b*b + delta )
The choice of esquared == delta == 1e-20 gives this a
colloquial English meaning of
"a and b agree to about 10 significant digits"
which is a reasonable version of "are approximately equal"
for doubles.
Carlie J. Coats, Jr. coats@ncsc.org *or* xcc@hpcc.epa.gov
MCNC Environmental Programs phone: (919)248-9241
North Carolina Supercomputing Center fax: (919)248-9245
3021 Cornwallis Road P. O. Box 12889
Research Triangle Park, N. C. 27709-2889 USA
"My opinions are my own, and I've got *lots* of them!"